<template>
  <div>
    <el-dialog
      v-model="dialogVisibleFlag"
      :title="props.isShareEditor == '0' ? '股东添加' : '股东修改'"
      width="80%"
      @close="handleClose"
      :close-on-click-modal="false"
    >
      <el-form :inline="true" :model="formList" ref="formRef" :rules="rules">
        <div v-for="(item, index) in formList.list" :key="index">
          <el-row>
            <el-col :span="6">
              <el-form-item
                label="人员"
                :prop="`list[${index}].people_id`"
                :rules="rules.people_id"
              >
                <el-select
                  :disabled="item.isDisadled"
                  v-model="item.people_id"
                  placeholder="请选择人员"
                >
                  <el-option
                    v-for="item in optionsList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item
                label="出资比例"
                :prop="`list[${index}].fund_ratio`"
                :rules="rules.fund_ratio"
              >
                <el-input
                  :disabled="item.isDisadled"
                  placeholder="请输入出资比例"
                  v-model="item.fund_ratio"
                  clearable
                  @change="
                    validateNumber(item.fund_ratio, index, item, 'fund_ratio')
                  "
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item
                label="认缴日期"
                style="width: 240px"
                :prop="`list[${index}].subscribe_time`"
                :rules="rules.subscribe_time"
              >
                <el-date-picker
                  :disabled="item.isDisadled"
                  style="width: 300px"
                  v-model="item.subscribe_time"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择企业成立时间"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item
                label="认缴金额(万元)"
                :prop="`list[${index}].subscribe_money`"
                :rules="rules.subscribe_money"
              >
                <el-input
                  :disabled="item.isDisadled"
                  placeholder="请输入认缴出资金额(万元)
              "
                  v-model="item.subscribe_money"
                  clearable
                  @change="
                    validateNumber(
                      item.subscribe_money,
                      index,
                      item,
                      'subscribe_money'
                    )
                  "
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item
                label="实缴金额(万元)"
                :prop="`list[${index}].practical_money`"
                :rules="rules.practical_money"
              >
                <el-input
                  :disabled="item.isDisadled"
                  placeholder="请输入实缴出资金额(万元)
                        "
                  v-model="item.practical_money"
                  clearable
                  @change="
                    validateNumber(
                      item.practical_money,
                      index,
                      item,
                      'practical_money'
                    )
                  "
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item
                label="持股比例"
                :prop="`list[${index}].shareholding_ratio`"
                :rules="rules.shareholding_ratio"
              >
                <el-input
                  :disabled="item.isDisadled"
                  placeholder="请输入持股比例

                        "
                  v-model="item.shareholding_ratio"
                  clearable
                  @change="
                    validateNumber(
                      item.shareholding_ratio,
                      index,
                      item,
                      'shareholding_ratio'
                    )
                  "
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item
                label="受益股份"
                :prop="`list[${index}].shareholding_beneficial`"
                :rules="rules.shareholding_beneficial"
              >
                <el-input
                  :disabled="item.isDisadled"
                  placeholder="请输入终受益股份比例

                        "
                  v-model="item.shareholding_beneficial"
                  clearable
                  @change="
                    validateNumber(
                      item.shareholding_beneficial,
                      index,
                      item,
                      'shareholding_beneficial'
                    )
                  "
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-button type="primary" @click="handleAdd">新增</el-button>
              <el-button
                type="success"
                :icon="useRenderIcon(Check)"
                circle
                :disabled="item.isDisadled"
                @click="addCompanyShareInsert(item, index)"
              />
              <el-button
                type="primary"
                v-if="gudongId"
                :icon="useRenderIcon(EditPen)"
                circle
                @click="handleEdit(item, index)"
              />
              <el-button
                type="danger"
                :icon="useRenderIcon(Delete)"
                icon="el-icon-delete"
                circle
                @click="handleDelete(index)"
              />
            </el-col>
          </el-row>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { getSessionKey } from "@/utils/auth";
import Refresh from "@iconify-icons/ep/refresh";
import Delete from "@iconify-icons/ep/delete";
import EditPen from "@iconify-icons/ep/edit-pen";
import Search from "@iconify-icons/ep/search";
import Check from "@iconify-icons/ep/check";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { message } from "@/utils/message";
import {
  peopleSelect,
  companyShareInsert,
  companyShareUpdate
} from "@/api/companyList";
import {
  reactive,
  ref,
  inject,
  onMounted,
  defineProps,
  defineEmits,
  nextTick,
  defineExpose,
  watch
} from "vue";
import { fa } from "element-plus/es/locale";
import { json } from "stream/consumers";
import { List } from "echarts/core";
const gudongId = ref("");
const dialogVisibleFlag = ref(false);
const listQuery = ref({});
const listQueryRef = ref("");
const formRef = ref("");
const props = defineProps({
  isShareEditor: {
    type: String,
    default: ""
  }
});
const rules = ref({
  people_id: [{ required: true, message: "请选择人员", trigger: "blur" }],
  fund_ratio: [{ required: true, message: "请输入出资比例", trigger: "blur" }],
  subscribe_time: [
    { required: true, message: "请选择认缴出资日期", trigger: "blur" }
  ],
  subscribe_money: [
    { required: true, message: "请输入认缴出资金额", trigger: "blur" }
  ],
  practical_money: [
    { required: true, message: "请输入实缴出资金额", trigger: "blur" }
  ],
  shareholding_ratio: [
    { required: true, message: "请输入持股比例", trigger: "blur" }
  ],
  shareholding_beneficial: [
    { required: true, message: "最终受益股份比例", trigger: "blur" }
  ]
});
onMounted(() => {
  getList();
});

// 打开弹框
const openShareEditorDialog = companyId => {
  dialogVisibleFlag.value = true;
  formList.value.list.map((el, i) => {
    el.company_id = companyId;
    el.isDisadled = false;
  });
};
// 提交

const getList = async () => {
  const obj = {
    name: ""
  };
  const res = await peopleSelect(obj);
  if (res.code == 200) {
    const dataList = res.data;
    optionsList.value = dataList;
  }
};
const handleDelete = index => {
  if (formList.value.list.length == 1) {
    message("暂无法删除", { type: "error" });
    return;
  }
  formList.value.list.splice(index, 1);
};
const optionsList = ref([]);
const formList = ref({
  list: [
    {
      people_id: "",
      fund_ratio: "",
      subscribe_time: "",
      subscribe_money: "",
      practical_money: "",
      shareholding_ratio: "",
      shareholding_beneficial: "",
      company_id: ""
    }
  ]
});
// 格式化
const validateNumber = (value, index, el, name) => {
  let newValue = value;
  const elInfo = JSON.parse(JSON.stringify(el));
  if (newValue) {
    newValue = newValue.toString();
    newValue = newValue.replace(/[^0-9.]/g, ""); ////清除"数字"和"."以外的字符
    newValue = newValue.replace(/^\./g, ""); //验证第一个字符是数字而不是点
    newValue = newValue.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的点
    newValue = newValue
      .replace(".", "$#$")
      .replace(/\./g, "")
      .replace("$#$", "."); //只保留第一个. 清除多余的点
    newValue = newValue.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3"); //只能输入两个小数
    newValue = Number(newValue);
    elInfo[name] = newValue;
    formList.value.list[index][name] = elInfo[name];
  }
};

// 编辑
const handleEdit = (item, i) => {
  formList.value.list.map((el, index) => {
    if (i == index) {
      el.isDisadled = false;
    }
  });
};
// 添加
const handleAdd = () => {
  formList.value.list.push({
    people_id: "",
    fund_ratio: "",
    subscribe_time: "",
    subscribe_money: "",
    practical_money: "",
    shareholding_ratio: "",
    shareholding_beneficial: "",
    company_id: ""
  });
};
// 股东保存提交按钮
const addCompanyShareInsert = (item, i) => {
  formRef.value.validate(valid => {
    if (valid) {
      if (!item.people_id) {
        message("请先选择人员", { type: "error" });
        return;
      }
      if (gudongId.value) {
        const itemData = JSON.parse(JSON.stringify(item));
        itemData.id = gudongId.value;
        const params = {
          ...itemData
        };
        delete params.isDisadled;
        companyShareUpdate(params).then(res => {
          if (res.code == 200) {
            message(res.msg, { type: "success" });
          }
        });
      } else {
        const params = JSON.parse(JSON.stringify(item));
        delete params.isDisadled;
        companyShareInsert(params).then(res => {
          if (res.code == 200) {
            gudongId.value = res.data;
            formList.value.list.map((el, index) => {
              if (i == index) {
                el.isDisadled = true;
              }
            });
            message(res.msg, { type: "success" });
          }
        });
      }
    } else {
      return false;
    }
  });
};
defineExpose({ openShareEditorDialog });
const handleClose = () => {
  dialogVisibleFlag.value = false;
};

const emit = defineEmits(["handleSubmit"]);
const handleSubmit = () => {
  listQueryRef.value.validate(valid => {
    if (valid) {
      // 添加
      const parmas = listQuery.value;
      // parmas.admin_id = getSessionKey().admin_id;
      emit("handleSubmit", parmas);
    }
  });
};
</script>

<style lang="scss" scoped></style>
